#include <signal.h>                                                
#include <unistd.h>

#include "rt.h"
	
Main ResTx;

void signal_isr( int sigint){
	
	if( sigint == SIGINT || sigint == SIGTERM || sigint == SIGPIPE) {
		printf("MAIN\tCerrando Proceso [%d] con senal [%d].\n", getpid(), sigint);                    
		ResTx.Stop();
	}
	else if( sigint == SIGUSR1 || sigint == SIGUSR2) { /// Reconfiguración aplicación.
		printf("MAIN\tReconfigurando aplicacion [%d] con senal [%d].\n", getpid(), sigint );
// 		App.ReloadConf();
	}
	else {
		printf("MAIN\tSe recibe senal no manejada [%d] sobre proceso[%d].\n", sigint, getpid());
	}
}               

void print_usage( char *procname){
	
        printf("uso:\t%s [-f] [-v] [-c <config>]\n", procname );
	printf("\t-f\trun in foreground, do not become daemon\n");
        printf("\t-v\tprint version and exit\n");                                                                                                                            
        printf("\t-c\tpathname for configuration file\n");     
}      

void print_version(){
	
        printf("Resource Transport Version : %s\n", VERSION );
        printf("Compiled on %s %s\nCopyright ©2011 Digisec Ltda. All rights reserved.\n", __DATE__, __TIME__ );
}                                                                                                                                 

int main( int argc, char *argv[] ){     
	
	bool fflag = false;
	int sid, pid;
	int c; 

	std::string cfile = "";
	
	while(( c = getopt (argc, argv, "vfc:")) != -1 ){

                switch ( c ) 
		{	
			case 'c':
				cfile = std::string( optarg );
				break;
			case 'f':
				fflag = true;
				break;
			case 'v':
				print_version();
				exit( EXIT_SUCCESS );
                        default:
                                print_usage( argv[0]);
                                exit( EXIT_FAILURE );
                }
        }

	if( cfile == "" )
	{
		print_usage( argv[0]);
		exit( EXIT_FAILURE );
	}
	
        signal( SIGINT, signal_isr );
        signal( SIGTERM, signal_isr );
	signal( SIGPIPE, signal_isr );
	
	signal( SIGUSR1, signal_isr );
	signal( SIGUSR2, signal_isr );
	
	if( fflag == false ) 
	{
		if(( pid = fork()) < 0 )
		{
		} 
		else if ( pid > 0) 
		{
			exit( EXIT_SUCCESS );
		}
		
		if(( sid = setsid()) < 0 )
		{
		}
	}
	
	try 
	{
		if( ResTx.Init( fflag, cfile ))
		{
			ResTx.Run();
		}
	}
	catch ( std::exception& e )
	{
		std::cerr << e.what() << std::endl;
	}
	
	return 0;
}

bool Main::Init( bool fflag, std::string cfile ) {

#if defined JSON_ATTRIBUTE
	read_json( cfile, Config );
#elif defined XML_ATTRIBUTE
	read_xml( cfile, Config );
#else
	#error No existe tipo de atributo definido (JSON,XML,INI )
#endif

	std::string logfile, level;
	if(( logfile = Config.get( "rt.debug.logfile", "" )) == "" )
	{
		printf( "[MAIN]\tThere is not logfile parameter in config file.\n" );
		fflag = true;
	}
	
	level = Config.get( "rt.debug.level", "error" );//log_strlevel[ ERROR ]);
// 	log_setlevel( log_getlevel(( char *) level.c_str( )));
	printf("CHeck %s:%s", logfile.c_str(), level.c_str());
	if( !fflag )
	{
		if( freopen( logfile.c_str(), "a", stdout) == NULL )
		{
			printf( "[MAIN]\tImposible redireccionar log hacia %s.\n", logfile.c_str());
		}
	}
	
	return true;
}

bool Main::Run() {
	
	return false;
}

void Main::Stop() {
	ReceivingFlag = false;
}

